package com.kasax.android.arch.utils.permissions;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;

import androidx.core.app.ActivityCompat;

import com.kasax.android.arch.BasicConstants;
import com.kasax.android.arch.utils.IntentUtils;
import com.kasax.android.arch.utils.LogUtils;
import com.kasax.android.arch.utils.DialogUtils;

import org.jetbrains.annotations.NotNull;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;

public class PermissionUtils {
    private static SoftReference<Activity> activitySoftReference;

    public static interface HandleCallback {
        // 低于6.0的会走此方法
        void skipPermissionRequest();
    }

    public static void injectContext(Activity activity) {
        activitySoftReference = new SoftReference<>(activity);
    }


    public static void requestSdcardPermission(HandleCallback callback) {
        Activity activity = activitySoftReference.get();
        int sdkInt = Build.VERSION.SDK_INT;
        LogUtils.e("requestSdcardPermission sdkInt: " + sdkInt);
        if (sdkInt >= Build.VERSION_CODES.M && sdkInt < Build.VERSION_CODES.R) {
            if (hasPermission(PermissionConstants.SDCARD_PERMISSON_GROUPS)) {
                // 有权限
                if (callback != null) {
                    callback.skipPermissionRequest();
                }
            } else {
                // 无权限
                requestPermission(PermissionConstants.SDCARD_PERMISSON_GROUPS,
                        PermissionConstants.NORMAL_PERMISSON_REQ_CODE, callback);
            }
        } else if (sdkInt >= Build.VERSION_CODES.R) {
            // Android11以上的设备
            // 判断是否有使用外部存储的权限
            boolean externalStorageManager = Environment.isExternalStorageManager();
            LogUtils.e(BasicConstants.LOG_TAG, "requestSdcardPermission externalStorageManager: " + externalStorageManager);
            if (externalStorageManager) {
                // 有权限
                if (callback != null) {
                    callback.skipPermissionRequest();
                }
            } else {
                // 跳转到手机设置
                IntentUtils.goRequestAppFileAccessPermissionPage(activity);
            }
        } else {
            // 有权限
            if (callback != null) {
                callback.skipPermissionRequest();
            }
        }
    }

    /**
     * 申请权限
     *
     * @param permissions
     * @param reqCode
     * @return
     */
    public static void requestPermission(String[] permissions, int reqCode, HandleCallback callback) {
        if (activitySoftReference.get() == null) {
            return;
        }
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            // androidM以下直接验证通过
            if (callback != null) {
                callback.skipPermissionRequest();
            }
        }

        activitySoftReference.get().requestPermissions(permissions, reqCode);
    }

    /**
     * 检查权限
     *
     * @param permissions
     * @return
     */
    public static List<Object> checkPermission(String[] permissions) {
        // 缓存没有检测失败的权限
        List<Object> result = new ArrayList<Object>();
        if (activitySoftReference.get() == null) {
            return result;
        }
        boolean isSuccess = true;
        StringBuilder sb = new StringBuilder();
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(activitySoftReference.get(), permission) != PackageManager.PERMISSION_GRANTED) {
                // 无权限
                sb.append(permission).append(",");
                // 有一个未通过就为false
                isSuccess = false;
            }
        }

        if (!isSuccess) {
            if (sb.length() > 0 && sb.toString().endsWith(",")) {
                sb.deleteCharAt(sb.length() - 1);
            }
            result.add(sb.toString());
        }
        // 结果在第一位
        result.add(0, isSuccess);
        return result;
    }

    /**
     * 是否有权限
     *
     * @param permissions
     * @return
     */
    public static boolean hasPermission(String[] permissions) {
        return (boolean) checkPermission(permissions).get(0);
    }

    /**
     * 处理权限申请结果
     */
    public static void handleOnRequestPermissionsResult(int requestCode, @NotNull String[] permissions,
                                                        boolean needRequestPermission, HandleCallback callback) {
        // 是否验证通过
        boolean permissionVerifySuccess = false;
        String titleStr = "";
        switch (requestCode) {
            case PermissionConstants.NORMAL_PERMISSON_REQ_CODE:
                List<Object> objects = checkPermission(permissions);
                Object verifyObj = objects.get(0);
                if (verifyObj instanceof Boolean) {
                    boolean verifyResult = (boolean) verifyObj;
                    if (!verifyResult) {
                        titleStr = permissions[0];
                    } else {
                        permissionVerifySuccess = true;
                    }
                }
                break;
        }
        if (permissionVerifySuccess) {
            if (callback != null) {
                callback.skipPermissionRequest();
            }
        } else {
            showTripDialog(titleStr, requestCode, permissions, needRequestPermission, callback);
        }

    }

    /**
     * intent的时候会走这里
     */
    public static void handleIntentPermissionRequestResult(int requestCode, int resultCode, HandleCallback callback) {
        // 是否验证通过
        boolean permissionVerifySuccess = false;
        String titleStr = "";
        switch (requestCode) {
            // 后面有了其它权限再添加
            case PermissionConstants.MANAGE_EXTERNAL_STORAGE_PERMISSON_REQ_CODE:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    boolean externalStorageManager = Environment.isExternalStorageManager();
                    LogUtils.e(BasicConstants.LOG_TAG,
                            "handleIntentPermissionRequestResult externalStorageManager: " + externalStorageManager);
                    if (externalStorageManager) {
                        permissionVerifySuccess = true;
                    } else {

                        titleStr = "MANAGE_EXTERNAL_STORAGE";
                    }
                }
                break;
        }
        if (permissionVerifySuccess) {
            if (callback != null) {
                callback.skipPermissionRequest();
            }
        } else {
            showTripDialog(titleStr, requestCode, new String[]{}, false, callback);
        }

    }

    public static void showTripDialog(String msg, int requestCode, @NotNull String[] permissions,
                                      boolean needRequestPermission, HandleCallback callback) {
        DialogUtils.show(
                activitySoftReference.get(),
                "温馨提示",
                "您拒绝了权限：" + msg + "会影响功能的正常使用," + "是否需要重新申请?",
                "需要",
                "不需要",
                new DialogUtils.Callback() {
                    @Override
                    public void onConfirm() {
                        if (needRequestPermission) {
                            LogUtils.e(BasicConstants.LOG_TAG, "onConfirm 重新申请权限");
                            // 是否需要重新申请
                            requestPermission(permissions, requestCode, callback);
                        } else {
                            LogUtils.e(BasicConstants.LOG_TAG, "onConfirm 啥都不做");
                        }
                    }

                    @Override
                    public void onCancel() {
                        // 啥都不做
                        LogUtils.e(BasicConstants.LOG_TAG, "啥都不做");
                    }
                });
    }


    public static void release() {
        activitySoftReference.clear();
    }

}
